<?php


namespace App\Models\Traits;

use App\Models\Goods;
use App\Models\Sharp;
use Illuminate\Support\Arr;

/**
 * Created By FreeAbrams
 * Date: 2020/12/25
 */
trait ReturnSharpStockWithoutSku
{
	/**
	 * @param array $goods_id
	 * @param int $sharp_id
	 * @return bool|int
	 */
	static public function prepareReturnStockWithoutSku($sharp_id = 0)
	{
		if (empty($sharp_id)) {
			return false;
		}
		$sharp = Sharp::with(['sharpGoods' => function ($q) {
			$q->whereNull('goods_sku_id')->where('stock', '>', 0);
		}])->find($sharp_id);
		
		if (empty($sharp->sharpGoods->toArray())) {
			return false;
		}
		
		$returns = $sharp->sharpGoods->pluck('stock', 'goods_id')->toArray();
		$goods = Goods::whereIn('id', array_keys($returns))->get(['id', 'stock']);
		foreach ($goods as $item) {
			static $data = [];
			$item->stock += Arr::get($returns, $item->id, 0);
		}
		$res = updateBatch('goods', $goods->toArray());
		return $res;
	}
	
	/**
	 * @param array $needs
	 * @return bool|int|string
	 */
	static public function prepareReduceStockWithoutSku($needs = [])
	{
		$goods = Goods::whereIn('id', array_keys($needs))->get(['id', 'stock', 'name']);
		
		if (empty($goods->toArray())) {
			return false;
		}
		
		foreach ($goods as $item) {
			$item->stock -= Arr::get($needs, $item->id, 0);
			
			if ($item->stock < 0) {
				return $item->name.'    库存不足';
			}
		}
		$res = updateBatch('goods', $item->toArray());
		
		if ($res) {
			return true;
		} else {
			return false;
		}
	}
}